// 将 HmThermometer 方法添加到 jQuery 的原型中
$.fn.extend({
  /**
   *
   * @param {
   * pulseData: 脉搏数据
   * temperatureData: 体温数据
   * breathData: 呼吸数据
   * mouthTemperature: 日期
   * inHospitalDate: 在院时间（开始-结束）
   * callback:回调函数
   *   } options
   * @returns
   */
  HmThermometer: function (options) {
    // --- 封装深拷贝方法，并添加到jquery上 start ----
    ;(function () {
      if (!$.deepCopyObj) {
        $.extend({
          deepCopyObj: function (ele) {
            var _t = this
            if (ele instanceof Array) {
              var result = []
              for (var i = 0; i < ele.length; i++) {
                result.push(_t.deepCopyObj(ele[i]))
              }
              return result
            } else if (ele instanceof Object && typeof ele != 'function') {
              var result1 = {}
              for (var key in ele) {
                result1[key] = _t.deepCopyObj(ele[key])
              }
              return result1
            } else {
              return ele
            }
          },
        })
      }
    })()
    // --- 封装深拷贝方法，并添加到jquery上  end ----

    var defaults = {
      temperatureData: [],
      breathData: [],
      pulseData: [],
      pressureData: [],
      pressureListTwo: [],
      shitData: [],
      InputData: [],
      OutputData: [],
      UrineOutputData: [],
      mouthTemperature: [],
      //三条折线颜色
      pigment: {
        breathColor: 'black',
        temperatureColor: 'blue',
        pulseColor: 'red',
      },
      //天数
      dayTemperature: [1, 2, 3, 4, 5, 6, 7],
    }
    //获取处理后的新dayTemperature ['第15天','第16天',....]
    options.dayTemperature = dayMap(
      options.inHospitalDate,
      options.mouthTemperature
    )
    var opts = $.extend({}, defaults, options)
    opts.container = this
    /*
     * 网格线组件使用时需要计算宽度
     * 建议整理好数据逻辑后直接传入
     * */
    // 前端配置不可删除

    // 底部数据
    var configFile = [
      '血压(mmHg)',
      ' ',
      '心率',
      '呼吸(次/分)',
      '大便(次/日)',
      '小便(次/日)',
      '入量 ml',
      '出量 ml',
      '尿量 ml',
      '身高(cm)',
      '体重(kg)',
      '过敏药物',
      '过敏药物2',
      '特殊治疗',
      '血糖(mmol/L)',
      '其他',
    ]
    // 中间展示维度
    var lefts = 20, // 左边距离
      tops = 120, // 上边距离 100
      rowSpacing = 18, // 每小格宽高度 15
      tRowNum = 2, // 头部行数(日期、住院天数)
      mRowNum = 42 // 中部行数(折线图📈中间部分)
    // 左侧坐标轴第一行数
    // 核心核心: 以时间 2 6 10 14 这条横线为基准的x轴0点和 y轴0点 开始画的,不要被标题的位移影响了!!!!
    // tops:120 为 时间 2 6 10 y轴到顶部的距离
    var YAxisDataTop = [
      {
        name: '脉 搏',
        position: [lefts + rowSpacing - 5, tops + rowSpacing - 10],
      },
      {
        name: '(次/分)',
        position: [lefts + rowSpacing - 5, tops + rowSpacing + 6],
      },
      {
        name: 180,
        position: [lefts + rowSpacing - 2, tops + 2 * rowSpacing + 5],
      },
      {
        name: '体 温',
        position: [lefts + 4 * rowSpacing - 5, tops + rowSpacing - 10],
      },
      {
        name: '(℃)',
        position: [lefts + 4 * rowSpacing, tops + rowSpacing + 6],
      },
      {
        name: 42,
        position: [lefts + 4 * rowSpacing + 3, tops + 2 * rowSpacing + 5],
      },
      {
        name: '呼 吸',
        position: [lefts + 7 * rowSpacing - 2, tops + rowSpacing - 10],
      },
      {
        name: '(次/分)',
        position: [lefts + 7 * rowSpacing - 6, tops + rowSpacing + 6],
      },
      {
        name: 90,
        position: [lefts + 7 * rowSpacing + 4, tops + 2 * rowSpacing + 5],
      },
    ]
    // 三测单左侧轴数据
    var YAxisData = [
      [160, 41, 80],
      [140, 40, 70],
      [120, 39, 60],
      [100, 38, 50],
      [80, 37, 40],
      [60, 36, 30],
      [40, 35, 20],
    ]
    /**
      计算传入的日期是，患者住院日期的第几天
      如:inHospitalDate['2021-12-15', '2022-01-01'] 
      inHospitalDate[0]开始住院日期 inHospitalDate[1]结束住院日期
      mouthTemperature['2021-12-15', '2021-12-16', '2021-12-17', '2021-12-18', '2021-12-19']
      返回：['第1天','第2天','第3天','第4天','第5天']
     */
    function dayMap(inHospitalDate, mouthTemperature) {
      var start = inHospitalDate[0],
        end = inHospitalDate[1]
      var allIn = getDates(start, end)
      var curDatesMap = {}
      $.each(mouthTemperature, function (i01, item01) {
        curDatesMap[item01] = 1
      })
      var result = []
      $.each(allIn, function (i, item) {
        if (curDatesMap[item]) {
          var cur = '第 ' + (i + 1) + ' 天'
          result.push(cur)
        }
      })
      function getDates(startDate, endDate) {
        var dates = []
        var current = moment(startDate)
        var end = moment(endDate)

        while (current <= end) {
          dates.push(current.format('YYYY-MM-DD'))
          current.add(1, 'days')
        }
        return dates
      }
      console.log(result, '---- result dayMap方法处理 ----')

      return result
    }
    var thermometer = {
      opts: opts,
      //初始化体温表
      init: function () {
        //   var _t = this
        //   opts.container.renderTpl('../tpl/echartsTm.html', {}, function () {
        //     //初始化配置
        //     _t.componentDidMount()
        //   })
        this.componentDidMount()
      },
      //初始化配置
      componentDidMount: function () {
        var self = this
        // lefts左边距离  top上边距离 rowSpacing每小格宽度 columnNum计算有多少列
        var tableDatas = {
          left: lefts,
          top: tops,
          rowSpacing: rowSpacing,
          columnNum: (7 + 1) * 6 + 3, // 51列
        }
        var whStyle = {
          height: tops + 50 + (mRowNum + configFile.length) * rowSpacing,
          width:
            lefts * 2 + ((7 + 1) * 6 + 3) * rowSpacing < 800
              ? 800
              : lefts * 2 + ((7 + 1) * 6 + 3) * rowSpacing,
          margin: 'auto',
        }
        $('#sk-orign-thermometer').css(whStyle)
        // 获取echarts 画板，最核心的方法，绘制图开始!!!!
        self.renderECharts(tableDatas, whStyle)
      },
      /**
       * 获取echarts 画板
       * @param {*
       *    tableDatas:[{lefts:0,top:0,rowSpacing:0,columnNum:0}] 配置数据对象 lefts左边距离  top上边距离 rowSpacing每小格宽度 columnNum计算有多少列
       *    whStyle:{height:0,width:0}, 高度和宽度
       *   } options
       * @returns
       */
      renderECharts: function (tableDatas, whStyle) {
        var self = this
        //整张图核心就是动态循环graphic里面的数据，[{type: 'line',...},{type: 'text',..},{type: 'circle',...}] line：折线，纵轴线，横轴线，text：文案，circle：圆点
        // 整合全部图表数据
        var tableData = self.getTableData(tableDatas) // 获取核心配置 graphic 需要的各个类型的图表 如 底部的血压、入量、头部的日期、时间、姓名、住院号等
        var myChart = echarts.init(
          document.getElementById('sk-orign-thermometer')
        )
        if (whStyle) {
          myChart._zr.painter._height = whStyle.height
          myChart._zr.painter._width = whStyle.width
        }
        myChart.clear()
        myChart.setOption({
          title: {
            show: true,
            text: '体 温 单',
            textStyle: {
              color: '#000',
              fontWeight: 'bold',
              fontSize: 22,
              align: 'left',
            },
            left: 'center',
            top: '20px',
          },
          toolbox: {
            // 工具箱 保存图片操作
            feature: {
              saveAsImage: {},
            },
            right: 30,
            top: 10,
          },
          tooltip: { show: true },
          graphic: tableData,
        })
        //兼容ie8
        window.onresize = myChart.resize
        myChart.resize()
        opts.callback && opts.callback(this, myChart)
        console.log($('#sk-orign-thermometer').children(':first'))
        $('#sk-orign-thermometer').children(':first').css('overflow', 'auto')
      },
      /**
       * 绘制图表
       * @param {*
       *    TSSParam:[{lefts:0,top:0,rowSpacing:0,columnNum:0}] 配置数据对象 left左边距离  tops上边距离 rowSpacing每小格宽度 columnNum计算有多少列
       *   } options
       * @returns
       */
      getTableData: function ($TSSParam) {
        var list = [], // 图表数组
          inspectionCycle = [2, 6, 10, 14, 18, 22], // 巡查间隔数组
          columnNum = $TSSParam.columnNum, // 列数
          bRowNum = configFile.length, // 尾部行数
          tDataKeys = ['日  期', '住院天数']
        //日期 天数
        var TimeDateList = this.getTabTime()
        /*获取头部部分：水平线 纵向线、以及文字数据录入*/
        var headerTextList = this.getHeaderTextList(tDataKeys, columnNum)
        /*坐标轴数据绘制 绘制 脉搏 体温 呼吸 （次/分）(℃)*/
        var yAxisList = this.getYAxisList()
        /*中间部分：水平线、纵向线、坐标轴以及数据录入*/
        var middleList = this.getMiddleList(columnNum, inspectionCycle)
        /*页脚部分：水平线、纵向线、以及文字 configFile:bDataKeys*/
        // var bottomList = this.getBottomList(configFile, bRowNum, columnNum);
        // list = list.concat(TimeDateList, headerTextList, yAxisList, middleList, bottomList);
        list = list.concat(TimeDateList, headerTextList, yAxisList, middleList)
        //折线数据
        //得到[x,y]轴坐标
        var coordinate = this.produceData(opts.breathData, 1) //呼吸
        var Tempernate = this.produceData(opts.temperatureData, 2) //体温
        var pulseTnate = this.produceData(opts.pulseData, 3) //脉搏
        //再把得到的【x,y】轴坐标直接加入echarts配置里面
        var breathingList = this.getBrokenLineList(
          coordinate,
          opts.pigment.breathColor
        ) //呼吸
        var temperaList = this.getBrokenLineList(
          Tempernate,
          opts.pigment.temperatureColor
        ) //体温
        var pulseList = this.getBrokenLineList(
          pulseTnate,
          opts.pigment.pulseColor
        ) //脉搏
        list = list.concat(breathingList, temperaList, pulseList)
        //圆点和折线坐标一摸一样
        var breathingDot = this.getDotList(
          coordinate,
          opts.pigment.breathColor,
          opts.breathData,
          '呼吸',
          '次/分'
        )
        var temperaDot = this.getDotList(
          Tempernate,
          opts.pigment.temperatureColor,
          opts.temperatureData,
          '体温',
          '(℃)'
        )
        var pulseDot = this.getDotList(
          pulseTnate,
          opts.pigment.pulseColor,
          opts.pulseData,
          '脉搏',
          '(次/分)'
        )
        list = list.concat(breathingDot, temperaDot, pulseDot)

        var bottomData = this.handleBottomData(opts.bottomList)
        var bottomList = this.createBottomTpl(bottomData)

        list = list.concat(bottomList)
        // //下面表格数据
        // var breathList = this.getTableList(opts.breathData, 1);// 呼吸
        // var pressureListTwo = this.getTableList(opts.pressureListTwo, 2);//血压第一条
        // var pressureList = this.getTableList(opts.pressureData, 3);//血压最后一条
        // var heartRateList = this.getTableList(opts.heartRateData, 4);//心率
        // var shitList = this.getTableList(opts.shitData, 5);//大便
        // var urinateList = this.getTableList(opts.urinateData, 6);// 小便
        // var InputList = this.getTableList(opts.InputData, 7);//入量
        // var OutputList = this.getTableList(opts.OutputData, 8);//出量
        // var UrineOutputList = this.getTableList(opts.UrineOutputData, 9);//尿量
        // var heightList = this.getTableList(opts.heightData, 10);//身高
        // var weightList = this.getTableList(opts.weightData, 11);//体重
        // var allergyMedicationsList = this.getTableList(opts.allergyMedicationsData, 12);//过敏药物
        // var allergyMedications2List = this.getTableList(opts.allergyMedications2Data, 13);//过敏药物2
        // var specialTreamentList = this.getTableList(opts.specialTreamentData, 14);//特殊治疗
        // var bloodSugarList = this.getTableList(opts.bloodSugarData, 15);//血压
        // var otherList = this.getTableList(opts.otherData, 16);//其他
        // list = list.concat(pressureListTwo, pressureList, shitList, InputList, OutputList, UrineOutputList, urinateList,heartRateList, breathList,heightList,weightList,allergyMedicationsList,allergyMedications2List,specialTreamentList,bloodSugarList,otherList);
        return list
      },
      /**
       * 构造数据
       * @param {*
       *    data:表数据
       *    type:1：呼吸 ,2:体温 ,3:脉搏
       *   } options
       * @returns
       */
      produceData: function (data, type) {
        var list = []
        for (var i = 0; i < data.length; i++) {
          if (!data[i][1]) {
            list.push([])
            continue
          }
          switch (type) {
            case 1:
              list.push([
                this.timeToX(data[i][0]),
                this.frequencyToY(data[i][1]),
              ])
              break
            case 2:
              list.push([
                this.timeToX(data[i][0]),
                this.temperatureToY(data[i][1]),
              ])
              break
            case 3:
              list.push([this.timeToX(data[i][0]), this.pulseToY(data[i][1])])
              break
            default:
              return []
          }
        }
        return list
      },
      //日期
      getTabTime: function () {
        var TimeList = []
        var first = ''
        var two = ''
        var mData = opts.mouthTemperature //日期数据 2022-01-01 ....
        var dData = opts.dayTemperature //天数数据 第x天 第x+1天 ....
        //日期
        for (var i = 0; i < mData.length; i++) {
          first += 6 * rowSpacing //文字离左边距离都是固定的
          var template = {
            type: 'text',
            top: tops - (tRowNum + 1) * rowSpacing + rowSpacing / 3, //固定参数
            left: first,
            cursor: 'auto',
            style: {
              text: mData[i],
              fontSize: '12px',
              color: '#000',
            },
          }
          //第一个的时候得加上左边全部的距离 left：20是图离echarts的外壳距离
          if (i == 0) {
            first = rowSpacing * 10 + lefts
            template.left = first
          }
          TimeList.push(template)
        }
        //天数
        for (var j = 0; j < dData.length; j++) {
          two += 6 * rowSpacing //文字离左边距离都是固定的
          var daytemplate = {
            type: 'text',
            top: tops - tRowNum * rowSpacing + rowSpacing / 3, //固定参数132
            left: two,
            cursor: 'auto',
            style: {
              text: dData[j],
              fontSize: '12px',
              color: '#000',
            },
          }
          //第一个的时候得加上左边全部的距离
          if (j == 0) {
            two = rowSpacing * 10 + lefts
            daytemplate.left = two
          }
          TimeList.push(daytemplate)
        }
        return TimeList
      },
      /*获取头部部分：水平线 纵向线、以及文字数据录入*/
      getHeaderTextList: function (tDataKeys, columnNum) {
        var listHTML = []
        // 绘制头部水平线 日期和住院天数 start
        for (var i = 0; i <= tRowNum; i++) {
          var leftDistance = 0,
            lineLength = 0
          //这里是头部超过三个的时候
          if (i > 2 && i !== tRowNum) {
            leftDistance = left + 6 * rowSpacing
            lineLength = (columnNum - 6) * rowSpacing
          } else {
            leftDistance = lefts
            lineLength = columnNum * rowSpacing
          }
          //画日期 住院天数 横线
          listHTML.push({
            type: 'line',
            top: tops + (i - 3) * rowSpacing, // 反向top负值往外走，时间底部那条线为tpo=0基准值
            left: leftDistance,
            cursor: 'auto',
            style: {
              stroke: !i ? '#000' : '#999',
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2: lineLength,
              y2: 0,
            },
          })
        }
        // 绘制头部水平线 日期和住院天数 end

        for (var j = 0; j <= columnNum; j++) {
          // 绘制纵向线 2021-12-15(日期到时间的两格纵线) start
          listHTML.push({
            type: 'line',
            top: tops - 3 * rowSpacing,
            left: lefts + j * rowSpacing,
            cursor: 'auto',
            style: {
              stroke: !j || j === columnNum ? '#000' : '#999',
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: !j || (j > 3 && !((j - 3) % 6)) ? tRowNum * rowSpacing : 0, //从j=9开始画,画2行的竖线
            },
          })
          // 绘制纵向线 2021-12-15(日期到时间的两格纵线) end

          // 添加头部数据文字 日期 和 住院天数 start
          if (!(j % 6)) {
            for (var k = 0; k < tRowNum; k++) {
              var template = {
                type: 'text',
                top: null,
                left: null,
                cursor: 'auto',
                style: {
                  text: null,
                  fontSize: '12px',
                  color: '#000',
                },
              }
              if (!j) {
                template.top =
                  tops - (tRowNum + 1 - k) * rowSpacing + rowSpacing / 3
                template.left = lefts + 5
                template.style.text = tDataKeys[k]
              } else {
                // 下面代码似乎不需要
                if (j === columnNum) break
                var count = j / 6
                template.top = tops - (tRowNum + 1 - k) * rowSpacing + 4
                template.left = lefts + (count * 6 + 3) * rowSpacing + 5
              }
              listHTML.push(template)
            }
          }
          // 添加头部数据文字 日期 和 住院天数 end
        }
        return listHTML
      },
      /* y轴坐标轴数据文字绘制 脉搏 体温 呼吸 (次/分)  (次/分) */
      getYAxisList: function () {
        var yAxisList = []
        for (var i = 0; i < YAxisDataTop.length; i++) {
          var stroke = '',
            fill = ''
          if (YAxisDataTop[i].name === '脉 搏') {
            stroke = fill = 'red'
          } else if (YAxisDataTop[i].name === '体 温') {
            stroke = fill = 'blue'
          } else {
            stroke = fill = '#000'
          }
          var template = {
            type: 'text',
            top: YAxisDataTop[i].position[1],
            left: YAxisDataTop[i].position[0],
            cursor: 'auto',
            style: {
              text: YAxisDataTop[i].name,
              fill: fill,
              fontSize: '12px',
              color: '#000',
              stroke: stroke,
            },
          }
          yAxisList.push(template)
        }
        return yAxisList
      },
      /*中间部分：水平线、纵向线、坐标轴以及数据录入*/
      // mRowNum行数，columnNum列数，inspectionCycle[2,6,10,14,18,22]时间间隔
      getMiddleList: function (columnNum, inspectionCycle) {
        var middleList = []
        for (var key = 0; key <= mRowNum; key++) {
          var leftDistance = 0,
            lineLength = 0
          //从 时间 底部 开始画x轴横线
          if (key > 2 && key !== mRowNum) {
            leftDistance = lefts + 9 * rowSpacing
            lineLength = (columnNum - 9) * rowSpacing
          } else {
            leftDistance = lefts
            lineLength = columnNum * rowSpacing
          }
          middleList.push({
            type: 'line',
            top: tops + (key - 1) * rowSpacing,
            left: leftDistance,
            cursor: 'auto',
            style: {
              stroke: key === mRowNum || !((key - 2) % 5) ? '#999' : '#ccc',
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2: lineLength,
              y2: 0,
            },
          })
          // 添加左侧y轴文字 80 70 60 50 40 30 20 10 0
          // 41 40 39 .....
          var count = Math.floor((key - 1) / 5) - 1
          if (
            key !== 2 &&
            key !== mRowNum &&
            (key - 1) % 5 === 1 &&
            count < 7
          ) {
            for (var keys = 0; keys < YAxisData[count].length; keys++) {
              var lDistance = 0
              if (keys == 0) {
                //调整如果是脉搏且是>=100则距离稍微大一点
                if (YAxisData[count][keys] >= 100) {
                  lDistance = lefts + rowSpacing - 2
                } else {
                  lDistance = lefts + rowSpacing + 2
                }
              } else if (keys == 1) {
                // 体温间隔
                lDistance = lefts + 4 * rowSpacing + 3
              } else {
                // 呼吸间隔
                lDistance = lefts + 7 * rowSpacing + 4
              }
              var template = {
                type: 'text',
                top: tops + (key - 1) * rowSpacing + 4,
                left: lDistance,
                cursor: 'auto',
                style: {
                  text: YAxisData[count][keys],
                  fontSize: '12px',
                  color: '#000',
                },
              }
              middleList.push(template)
            }
          }
        }
        for (var index = 0; index <= columnNum; index++) {
          var lineLength = 0
          if (index >= 9 || index === 0 || index === 3 || index === 6) {
            if (index === 3 || index === 6)
              lineLength = (mRowNum - 1) * rowSpacing
            else lineLength = mRowNum * rowSpacing
          }
          var $stroke
          if (!((index - 3) % 6)) {
            if (index === columnNum) $stroke = '#000'
            else if (index === 3 || index === 6) $stroke = '#999'
            else $stroke = 'red'
          } else {
            if (!index || index === columnNum) $stroke = '#000'
            else if (index === 6) $stroke = '#999'
            else $stroke = '#ccc'
          }
          middleList.push({
            type: 'line',
            cursor: 'auto',
            top: index === 3 || index === 6 ? tops : tops - rowSpacing,
            left: lefts + index * rowSpacing,
            style: {
              stroke: $stroke,
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: lineLength,
            },
          })

          /*添加巡查时间刻度*/
          var template = {
            type: 'text',
            top: tops - 10,
            left:
              inspectionCycle[index % 6] >= 10
                ? lefts + (index + 3) * rowSpacing + 5 // why(index+3)??? 之所以+3可能是因为lefts值大概是3格
                : lefts + (index + 3) * rowSpacing + 7,
            cursor: 'auto',
            style: {
              text: inspectionCycle[index % 6],
              fontSize: '12px',
              color: '#000',
            },
          }
          if (index >= 6 && index < columnNum - 3) {
            middleList.push(template)
          } else if (index === 0) {
            template.left = lefts + 5
            template.style.text = '时间'
            middleList.push(template)
          }
        }
        return middleList
      },
      // 处理底部表格列表数据,
      handleBottomData: function (bottomDataOrigin) {
        var bottomData = $.deepCopyObj(bottomDataOrigin)
        for (var i = 0; i < bottomData.length; i++) {
          var cur = bottomData[i],
            data = cur.data,
            rowspan = cur.rowspan || 1,
            colspan = cur.colspan || 6,
            res = serializeData(data, { r: rowspan, c: colspan })
          cur.data = res
        }

        // 序列化数据，缺天数数据，补天数数据
        function serializeData(data, conf) {
          // 处理colspan
          var colDateTpl = {
              1: {
                list: ['02', '06', '10', '14', '18', '22'],
                data: {
                  '23,00,01,02,': '02',
                  '03,04,05,06': '06',
                  '07,08,09,10': '10',
                  '11,12,13,14': '14',
                  '15,16,17,18': '18',
                  '19,20,21,22': '22',
                },
              },
            },
            timeTplObj = colDateTpl[conf.c]

          var dataMap = {} // 将数据转为map结构 方便后续操作
          $.each(data, function (i, item) {
            var key = moment(item[0]).format('YYYY-MM-DD'),
              val = item[1]
            if (timeTplObj) {
              var hh = moment(item[0]).format('HH'),
                hhs = ''
              for (var lk in timeTplObj.data) {
                var th = timeTplObj.data[lk]
                if (lk.indexOf(hh) > -1) {
                  hhs = th
                }
              }
              key = key + ' ' + hhs
            }
            while (dataMap[key]) {
              key += 'repeat'
            } // 重复数据打上标记-- 对应一天中多条数据展示的
            dataMap[key] = val
          })

          var baseDateList = opts.mouthTemperature // 基础日期序列
          var dateList = [] // 实际日期序列
          var res = [] // 最终数据
          if (timeTplObj) {
            var ddList = timeTplObj.list
            $.each(baseDateList, function (i02, item02) {
              $.each(ddList, function (i03, item03) {
                var newItem = item02 + ' ' + item03
                dateList.push(newItem)
              })
            })
          } else {
            dateList = baseDateList
          }
          var rStr = ''
          for (var m = 0; m < conf.r; m++) {
            var tempRes = []
            $.each(dateList, function (i01, item01) {
              var value = dataMap[item01 + rStr] || ''
              tempRes.push(value)
            })
            res.push(tempRes)
            rStr += 'repeat'
          }
          return res
        }
        return bottomData
      },
      // 生成底部表格列表模板和数据
      createBottomTpl: function (bottomData) {
        var _t = this

        var bottomList = [],
          btmTop = tops + (mRowNum - 1) * rowSpacing, // 底部y起始
          dataLen = bottomData.length,
          finalRows = dataLen,
          columnNum = (7 + 1) * 6 + 3,
          colWidth = columnNum * rowSpacing, // 整体列宽
          theadWidth = 9 * rowSpacing, // 表头宽度
          theadRight = theadWidth + lefts // 表头结束位置
        // 线条形状 - 后续拷贝
        var lineBase = {
          type: 'line',
          cursor: 'auto',
          left: lefts,
          top: btmTop,
          shape: {
            x1: 0,
            y1: 0,
            x2: 0,
            y2: 0,
          },
          style: {
            stroke: '#999',
            lineWidth: 1,
          },
        }

        var rowPosi = 0 // rowspan 位置

        for (var i = 0; i < bottomData.length; i++) {
          var cur = bottomData[i],
            title = cur.title, // 当前行标题，即表头
            rowspan = cur.rowspan || 1, // 默认一个字段一行
            curTop = btmTop + (rowPosi + i) * rowSpacing,
            tbodyData = cur.data,
            colspan = cur.colspan || 6 // 默认一个字段数据为7条（即每天1条数据）

          // 绘制表框 横向
          var rowLineObj = $.deepCopyObj(lineBase)
          rowLineObj.shape.x2 = colWidth
          rowLineObj.top = curTop

          var isIE = _t.isIE()
          // 文本基础
          var textLeft = lefts + 5,
            textTop = curTop + (isIE ? 5 : rowSpacing / 2)
          var textBase = {
            type: 'text',
            top: textTop,
            left: textLeft,
            cursor: 'auto',
            style: {
              text: title,
              fontSize: '12px',
              color: '#000',
            },
          }
          // 表头数据
          var theadTextObj = $.deepCopyObj(textBase)

          // 有合并行
          if (rowspan - 1) {
            for (var j = 0; j < rowspan; j++) {
              var rowCurTop = curTop + j * rowSpacing
              var rowspanLine = $.deepCopyObj(lineBase)
              rowspanLine.shape.x2 = colWidth - theadWidth
              rowspanLine.top = rowCurTop
              rowspanLine.left = theadRight
              bottomList.push(rowspanLine)

              // 合并单元格创建文本
              createTbodyData(
                tbodyData[j],
                rowCurTop + (isIE ? 5 : rowSpacing / 2),
                rowCurTop,
                colspan
              )
            }
            // 表头文本 按rowspan居中
            theadTextObj.top = curTop + (rowspan * rowSpacing) / 2

            finalRows += rowspan - 1
            rowPosi += rowspan - 1
            curTop += (rowspan - 1) * rowSpacing
          } else {
            createTbodyData(tbodyData[0], textTop, curTop, colspan)
          }
          bottomList.push(rowLineObj, theadTextObj)

          // 外围框
          if (i === dataLen - 1) {
            // thead right
            var theadRightObj = $.deepCopyObj(rowLineObj)
            theadRightObj.top = tops + (mRowNum - 1) * rowSpacing
            theadRightObj.left = theadRight
            theadRightObj.shape.y2 = finalRows * rowSpacing
            theadRightObj.shape.x2 = 0

            // 下
            var btmLineObj = $.deepCopyObj(rowLineObj)
            btmLineObj.top = btmTop + finalRows * rowSpacing
            btmLineObj.style.stroke = '#000'

            // 左
            var leftLineObj = $.deepCopyObj(btmLineObj)
            leftLineObj.shape.x2 = 0
            leftLineObj.top = tops + (mRowNum - 1) * rowSpacing
            leftLineObj.shape.y2 = finalRows * rowSpacing

            // 右
            var rightLineObj = $.deepCopyObj(leftLineObj)
            rightLineObj.left = colWidth + lefts

            bottomList.push(
              btmLineObj,
              leftLineObj,
              rightLineObj,
              theadRightObj
            )
          }
        }
        // 创建tbody文本数据
        function createTbodyData(arr, textTop, rowTop, colspan) {
          // 画数据边框线 根据 colspan 画
          var totalCount = 6 * 7, // 总共的数据格数
            needBorderCount = Math.floor(totalCount / colspan), // 根据colspan计算后所需的边框数
            borderSpace = 0,
            borderRight = $.deepCopyObj(lineBase)

          borderRight.style.stroke = '#ccc'
          borderRight.top = rowTop
          borderRight.shape.y2 = rowSpacing

          for (var n = 0; n < needBorderCount; n++) {
            var curBorder = $.deepCopyObj(borderRight)
            curBorder.left = theadRight + borderSpace
            borderSpace += colspan * rowSpacing
            bottomList.push(curBorder)
          }

          // 塞入文本
          var first = 0
          for (var k = 0; k < arr.length; k++) {
            var text = arr[k],
              textLen = _t.textLength(text),
              sliceLen = isIE ? 6 : 8,
              omitText = textLen > 15 ? text.slice(0, sliceLen) + '...' : text, // 只显示前10个字符和省略号
              tbodyTextObj = $.deepCopyObj(textBase)

            tbodyTextObj.left = theadRight + (isIE ? 2 : 5) + first
            tbodyTextObj.top = textTop
            tbodyTextObj.style.text = omitText
            if (textLen > 15) {
              wrpText = _t.wrpText(text)
              tbodyTextObj.tooltip = {
                formatter: wrpText,
              }
            }

            first += colspan * rowSpacing
            bottomList.push(tbodyTextObj)
          }
        }

        return bottomList
      },
      // 文字长度，中文*2
      textLength: function (text) {
        var reg = /[^\x00-\xff]/gi //判断是否存在中文和全角字符
        var resLen = 0
        text = text || ''
        for (var i = 0; i < text.length; i++) {
          resLen = resLen + (reg.test(text[i]) ? 2 : 1)
        }
        return resLen
      },
      wrpText: function (text) {
        var resText = ''
        for (var tl = 0; tl < text.length; tl += 8) {
          resText += text.slice(tl, tl + 10) + '<br/>'
        }
        return resText
      },
      isIE: function () {
        var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
        var isIE =
          userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 //判断是否IE<11浏览器
        return isIE
      },
      /*页脚部分：水平线、纵向线、以及文字*/
      getBottomList: function (bDataKeys, bRowNum, columnNum) {
        var bottomList = []
        //水平线
        for (var keys = 0; keys <= bRowNum; keys++) {
          var topData = tops + (mRowNum + keys - 1) * rowSpacing
          bottomList.push({
            type: 'line',
            cursor: 'auto',
            //mRowNum 42中部行数 keys=1时 血压要占二格数据;
            top: topData,
            left: keys == 1 ? lefts + rowSpacing * 9 : lefts,
            style: {
              stroke: keys === bRowNum ? '#000' : '#999',
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2:
                keys == 1
                  ? (columnNum - 9) * rowSpacing
                  : columnNum * rowSpacing,
              y2: 0,
            },
          })
        }
        //纵向线
        for (var indexs = 0; indexs <= columnNum; indexs++) {
          var lineLength = 0
          if (indexs >= 9) {
            if (!((indexs - 3) % 6)) {
              lineLength = bRowNum * rowSpacing
            } else {
              lineLength = rowSpacing
            }
            //第一行每行中间出现横杠 暂时不需要
            // else if (!(indexs % 3)) {
            //    lineLength = rowSpacing;
            // }
          } else if (indexs === 0) {
            lineLength = bRowNum * rowSpacing
          }
          bottomList.push({
            type: 'line',
            cursor: 'auto',
            top: tops + (mRowNum - 1) * rowSpacing,
            left: lefts + indexs * rowSpacing,
            style: {
              stroke: !indexs || indexs === columnNum ? '#000' : '#999',
              lineWidth: 1,
            },
            shape: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: lineLength,
            },
          })
          // 添加页脚数据集
          if (!(indexs % 6)) {
            var count = indexs / 6
            for (var k = 0; k < bRowNum; k++) {
              if (indexs === columnNum) break
              if (!count) {
                // 第一列
                var template = {
                  type: 'text',
                  top: null,
                  left: null,
                  cursor: 'auto',
                  style: {
                    text: null,
                    fontSize: '12px',
                    color: '#000',
                  },
                }
                var textTop =
                  tops + (mRowNum - 1 + k) * rowSpacing + rowSpacing / 3
                //k == 0是血压文字在中间
                template.top = k == 0 ? textTop + rowSpacing / 2 : textTop
                template.left = lefts + 5
                template.style.text = bDataKeys[k]
                bottomList.push(template)
              }
            }
          }
        }
        return bottomList
      },
      //整合折线
      getBrokenLineList: function (data, pigment) {
        var zhexianList = []
        var template = {}
        for (var i = 0; i < data.length; i++) {
          if (data[i + 1] && data[i + 1].length) {
            template = {
              type: 'line',
              shape: {
                x1: data[i][0], //第一个折线点 x轴
                y1: data[i][1], //第一个折线点 y轴
                x2: data[i + 1][0], //第二个折线点 x轴
                y2: data[i + 1][1], //第二个折线点 y轴
              },
              style: {
                fill: null,
                stroke: pigment,
                lineWidth: 1,
              },
            }
          } else {
            //下一条数据没有就换成圆点就行
            template = {
              type: 'circle',
              shape: {
                cx: data[i][0],
                cy: data[i][1],
                r: 2,
              },
              style: {
                fill: null,
                stroke: pigment,
                lineWidth: 1,
              },
            }
          }
          zhexianList.push(template)
        }
        return zhexianList
      },
      //圆点
      getDotList: function (data, pigment, list, text, Company) {
        var yuandianList = []
        //存储鼠标滑上去的内容数组
        var tooltipArr = []
        var ciNum = null
        //一个小时内有二条数据，折线点就会重叠，鼠标滑上去就显示一条数据，这里把二条数据都一起显示
        for (var j = 0; j < list.length; j++) {
          if (ciNum == j) {
            continue
          }
          if (data[j + 1] && data[j + 1].length) {
            //有下一条数据
            if (list && list[j + 1]) {
              var tiemFirst = list[j][0].replace(/-/g, '/')
              var currentDate = new Date(
                Date.parse(tiemFirst.replace(/-/g, '/'))
              )
              var tiemNext = list[j + 1][0].replace(/-/g, '/')
              var starttime = new Date(Date.parse(tiemNext.replace(/-/g, '/')))
              currentDate = Number(currentDate)
              starttime = Number(starttime)
              var laterHour = Math.round(
                (starttime - currentDate) / 1000 / 60 / 60
              ) //一定要四舍五入不然格子算不准 /1000:秒/60:分钟/60:小时
              if (!laterHour) {
                ciNum = j + 1 //记录下一次就不去循环了，下一条数据已经有了
                tooltipArr[j] =
                  list[j][0] +
                  text +
                  '：' +
                  list[j][1] +
                  Company +
                  '</br>' +
                  list[j + 1][0] +
                  text +
                  '：' +
                  list[j + 1][1] +
                  Company
                tooltipArr[j + 1] =
                  list[j][0] +
                  text +
                  '：' +
                  list[j][1] +
                  Company +
                  '</br>' +
                  list[j + 1][0] +
                  text +
                  '：' +
                  list[j + 1][1] +
                  Company
              } else {
                tooltipArr[j] =
                  list[j][0] + '</br>' + text + '：' + list[j][1] + Company
                ciNum = ''
              }
            }
          } else {
            tooltipArr[j] =
              list[j][0] + '</br>' + text + '：' + list[j][1] + Company
          }
        }
        for (var i = 0; i < data.length; i++) {
          var template = {
            type: 'circle',
            shape: {
              cx: data[i][0],
              cy: data[i][1],
              r: 2,
            },
            tooltip: {
              trigger: 'item',
              formatter: tooltipArr[i],
            },
            style: {
              fill: null,
              stroke: pigment,
              lineWidth: 1,
            },
          }
          yuandianList.push(template)
        }
        return yuandianList
      },
      //底部表格
      getTableList: function (data, type) {
        var tableList = []
        var first = ''
        //日期
        for (var i = 0; i < data.length; i++) {
          first += 6 * rowSpacing //文字离左边距离都是固定的
          var text =
            type == 1 || type == 2
              ? data && data[i]
                ? data[i].diastolicPressure + '/' + data[i].systolicPressure
                : ''
              : data[i][1]
          // 只显示前10个字符和省略号
          var textData =
            text && text.length > 10 ? text.slice(0, 10) + '...' : text
          var template = {
            type: 'text',
            top: (44 + type) * rowSpacing + tops - 54,
            left: first,
            cursor: 'auto',
            style: {
              text: textData,
              fontSize: '12px',
              color: '#000',
            },
          }
          if (text && text.length > 10) {
            template.tooltip = {
              trigger: 'item',
              formatter: text,
            }
          }
          //第一个的时候得加上左边全部的距离 left：20是图离echarts的外壳距离
          if (i == 0) {
            first = rowSpacing * 10 + lefts
            template.left = first
          }
          tableList.push(template)
        }
        return tableList
      },
      // 呼吸转化为y轴坐标
      frequencyToY: function (frequency) {
        //得到离90的距离多少格子 向下取整
        var remainder = (90 - frequency) / 2
        //不是偶数就得到格子得一半
        var multiplier = frequency % 2 == 0 ? 0 : remainder % 2 == 0 ? 0 : 5
        return Math.floor(remainder) * rowSpacing + tops + 20 + multiplier
      },
      // 时间日期转化为x轴坐标
      timeToX: function (time) {
        var startDate = opts.mouthTemperature[0] + ' 00:00:00'
        //兼容ie8 时间必须是0000/00/00才能计算
        var currentDate = new Date(Date.parse(time.replace(/-/g, '/')))
        var starttime = new Date(Date.parse(startDate.replace(/-/g, '/')))
        currentDate = Number(currentDate)
        starttime = Number(starttime)
        var linegezi = rowSpacing * 9 + lefts //前面有9个格子加到图表壳子的20距离
        var laterHour = Math.round((currentDate - starttime) / 1000 / 60 / 60) // 一定要四舍五入不然格子算不准 /1000:秒/60:分钟/60:小时
        var laterNum = laterHour * ((6 * rowSpacing) / 24) //每小时在格子上面的距离
        return linegezi + laterNum
      },
      // 体温转化为y轴坐标
      temperatureToY: function (temperature) {
        //得到离42的距离多少格子 ps:substr(-1) ie8不兼容
        var tempStr = (temperature * 10).toString()
        var later = tempStr.substr(tempStr.length - 1, 1)
        later === '0' && (later = 10)
        return (
          Math.floor(42 - temperature) * 5 * rowSpacing +
          ((10 - later) / 2) * rowSpacing +
          tops +
          20
        )
      },
      // 脉搏转化为y轴坐标
      pulseToY: function (pulse) {
        //得到离180的距离多少格子
        var remainder = (180 - pulse) / 4
        //不是偶数就得到格子得一半
        var multiplier = remainder % 2 == 0 ? 0 : 10
        return (
          Math.ceil((180 - pulse) / 4) * rowSpacing + tops + 20 - multiplier
        )
      },
    }
    thermometer.init()
    return thermometer
  },
})
